package com.example.crm.web.controller;

import com.example.crm.config.shiro.MyShiroRealm;
import com.example.crm.entity.Right;
import com.example.crm.entity.Role;
import com.example.crm.entity.User;
import com.example.crm.service.IRoleService;
import com.example.crm.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author lenovo
 */
@Controller
public class IndexController {
    @Resource
    private IRoleService roleService;
    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * redis中数据的key的前缀
     */
    private String SHIRO_LOGIN_COUNT = "shiro_login_count_";

    /**
     * 登录页面
     * @return
     */
    @RequestMapping("/index")
    public String index() {
        return "login";
    }

    /**
     * 登录方法
     * @param usrName
     * @param usrPassword
     * @param model
     * @param request
     * @param session
     * @return
     */
    @RequestMapping("/login")
    public String login(String usrName, String usrPassword, Model model, HttpServletRequest request, HttpSession session) {
        try {
            //封装之前先进行加密
            //usrPassword = userService.encryptPassword(usrPassword);
            UsernamePasswordToken token = new UsernamePasswordToken(usrName, usrPassword);
            Subject subject = SecurityUtils.getSubject();
            //认证、登录
            subject.login(token);
            //认证(登录)成功，清空登录计数
            stringRedisTemplate.delete(SHIRO_LOGIN_COUNT + usrName);
            //认证(登录)成功
            User user = (User) subject.getPrincipal();
            //获取权限
            //如果一对多关联不是立即加载，则需要通过用户获取角色
            Role role = user.getRole();
            List<Right> rights = roleService.findRightsByRole(role);
            role.getRights().addAll(rights);
            request.getSession().setAttribute("loginUser", user);
            //清空权限缓存
            RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
            MyShiroRealm realm = (MyShiroRealm) rsm.getRealms().iterator().next();
            realm.clearMyCachedAuthorizationInfo();
            //重定向
            return "redirect:/main";
        } catch (UnknownAccountException | IncorrectCredentialsException e) {
            model.addAttribute("message", "用户名或密码错误，登录失败！");
            return "login";
        } catch (LockedAccountException e) {
            model.addAttribute("message", "用户被禁用，登录失败！");
            return "login";
        } catch (AuthenticationException e) {
            model.addAttribute("message", "认证异常，登录失败！");
            return "login";
        }
    }

    /**
     * 主页
     * @return
     */
    @RequestMapping("/main")
    public String main() {
        return "main";
    }

    /**
     * 退出
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("loginUser");
        //shiro注销
        SecurityUtils.getSubject().logout();
        //重定向，保证删除Cookie
        return "redirect:/index";
    }

    /**
     * 403页面
     * @return
     */
    @RequestMapping("/403")
    public String unauthorized(){
        return "403";
    }
}